import { getQuery } from 'h3';
import { ArticleModel, IArticle } from '~/server/models/article.model';

// 获取文章列表
export default defineEventHandler(async (event): Promise<any> => {
	try {
		const query = getQuery(event);
		const keyword = query.keyword ? String(query.keyword) : '';
		const category = query.category ? String(query.category) : '';
		const currentPage = Number(query.currentPage) > 0 ? Number(query.currentPage) : 1;
		const pageSize = Number(query.pageSize) > 0 ? Number(query.pageSize) : 10;

		// 构建搜索条件
		const filter: any = {};
		if (keyword && category) {
			filter.$or = [
				{ title: { $regex: keyword, $options: 'i' } },
				{ content: { $regex: keyword, $options: 'i' } },
			];
			filter.categoryId = category;
		} else if (keyword) {
			filter.$or = [
				{ title: { $regex: keyword, $options: 'i' } },
				{ content: { $regex: keyword, $options: 'i' } },
			];
		} else if (category) {
			filter.categoryId = category;
		}

		// 获取总数
		const total = await ArticleModel.countDocuments(filter);

		// 查询文章，分页 + 分类信息
		const articles = await ArticleModel.find(filter)
			.populate('categoryId', 'name')
			.sort({ createdAt: -1 })
			.skip((currentPage - 1) * pageSize)
			.limit(pageSize)
			.lean();

		const list = articles.map((item: any) => {
			const { categoryId, ...rest } = item;
			return {
				...rest,
				content: item.content.slice(0, 300) + '...',
				category: categoryId ? { _id: categoryId._id, name: categoryId.name } : null,
			};
		});

		return {
			code: 1,
			message: '获取成功',
			data: { list, total },
		};
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
